﻿using System;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Renren.Helpers;
using Renren.Xna;

namespace Renren.Pages
{
    public partial class NewPhotoPage : PhoneApplicationPage
    {
        private ContentManager cm;
        private GameTimer timer;
        private SpriteBatch sb;
        private UIElementRenderer er;

        private Photo photo;

        public NewPhotoPage()
        {
            InitializeComponent();

            TouchPanel.EnabledGestures =
                GestureType.Hold |
                GestureType.Tap |
                GestureType.DoubleTap |
                GestureType.FreeDrag |
                GestureType.Flick |
                GestureType.Pinch;

            // Get the content manager from the application
            cm = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();            
            timer.UpdateInterval = TimeSpan.FromTicks(33333);

            // Using TimeSpan.Zero causes the update to happen 
            // at the actual framerate of the device. This makes 
            // animation much smoother. However, this will cause 
            // the speed of the app to vary from device to device 
            // where a fixed UpdateInterval will not.
            timer.UpdateInterval = TimeSpan.Zero;

            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            // Use the LayoutUpdate event to know when the page layout 
            // has completed so we can create the UIElementRenderer
            LayoutUpdated += (s, e) =>
                {
                    // Create the UIElementRenderer to draw the XAML page to a texture.

                    // Check for 0 because when we navigate away the LayoutUpdate event
                    // is raised but ActualWidth and ActualHeight will be 0 in that case.
                    if (ActualWidth > 0 && ActualHeight > 0 && er == null)
                    {
                        er = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
                    }
                };
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            sb = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            if (null == photo)
            {
                photo = new Photo("http://www.travelblog.org/Wallpaper/pix/tb_fiji_sunset_wallpaper.jpg");
            }

            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        public void OnUpdate(object sender, GameTimerEventArgs e)
        {
            TouchCollection touches = TouchPanel.GetState();

            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gesture = TouchPanel.ReadGesture();

                switch (gesture.GestureType)
                {
                    case GestureType.FreeDrag:
                        var p = photo.Position + gesture.Delta;
                        if ((p.X - photo.Texture.Width * photo.Scale / 2) <= 0 &&
                            (p.X + photo.Texture.Width * photo.Scale / 2) >= 480)
                        {
                            photo.Position = new Vector2(p.X, photo.Position.Y);
                        }
                        if ((p.Y - photo.Texture.Height * photo.Scale / 2) <= 0 &&
                            (p.Y + photo.Texture.Height * photo.Scale / 2) >= 800)
                        {
                            photo.Position = new Vector2(photo.Position.X, p.Y);
                        }
                        //photo.Position = p;
                        break;

                    // on flicks, we want to update the selected sprite's velocity with
                    // the flick velocity, which is in pixels per second.
                    case GestureType.Flick:
                        photo.Velocity = gesture.Delta;
                        break;
                    case GestureType.Pinch:
                        // get the current and previous locations of the two fingers
                        Vector2 a = gesture.Position;
                        Vector2 aOld = gesture.Position - gesture.Delta;
                        Vector2 b = gesture.Position2;
                        Vector2 bOld = gesture.Position2 - gesture.Delta2;

                        // figure out the distance between the current and previous locations
                        float d = Vector2.Distance(a, b);
                        float dOld = Vector2.Distance(aOld, bOld);

                        // calculate the difference between the two and use that to alter the scale
                        float scaleChange = (d - dOld) * .01f;
                        var s = photo.Scale + scaleChange;
                        if (s > photo.MaxScale)
                        {
                            photo.Scale = photo.MaxScale;
                        }
                        else if (s < photo.MinScale)
                        {
                            photo.Scale = photo.MinScale;
                        }
                        else
                        {
                            photo.Scale = s;
                        }
                        break;
                }
            }
        }

        public void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);

            // Render the Silverlight controls using the UIElementRenderer
            er.Render();

            // Draw the sprite
            sb.Begin();

            if (null != photo)
            {
                // Draw the rectangle in its new position
                sb.Draw(photo);
            }

            // Using the texture from the UIElementRenderer, 
            // draw the Silverlight controls to the screen
            sb.Draw(er.Texture, Vector2.Zero, Color.White);

            sb.End();
        }
    }
}